package cn.hl.hm.handler;

import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.vizhuo.utils.DateUtil;

import cn.hl.hm.constants.OrderStatus;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.constants.WeixinPayConfig;
import cn.hl.hm.entity.Coupon;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.Order;
import cn.hl.hm.entity.Push;
import cn.hl.hm.entity.UnifiedOrderRequest;
import cn.hl.hm.entity.UnifiedOrderRespose;
import cn.hl.hm.service.OrderService;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.util.NumberUtils;
import cn.hl.hm.util.SignWX;
import cn.hl.hm.util.WXUtil;

/**
 * 微信APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class WxAppPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(WxAppPayHandler.class);
	@Autowired
	@Qualifier("weixinpayConfig")
	private WeixinPayConfig weixinpayConfig;

	@Autowired
	@Qualifier("weixinpayConfigIosQYB")
	private WeixinPayConfig weixinpayConfigIosQYB;

	@Autowired
	private OrderService orderService;

	@Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;

	/**
	 * 处理微信支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		String orderCode = payMap.get("orderCode");
		String iosFlag = payMap.get("iosFlag");

		HashMap<String, String> map = new HashMap<String, String>();
		

		// 支付参数
		String nonceStr = SignWX.create_nonce_str();
		String ip = WXUtil.getLocalNetWorkIp();
		String seconds = WXUtil.getTimeStamp();
		UnifiedOrderRequest uor = new UnifiedOrderRequest();
		// 01 找订单 TODO
		Order toe = new Order();

		Order orderParam = new Order();
		orderParam.setOrderCode(orderCode);
		List<Order> selectOrder = orderService.selectOrder(orderParam);
		if (selectOrder != null && selectOrder.size() > 0) {
			toe = selectOrder.get(0);
		} else {
			return map;
		}

		WeixinPayConfig config = null;
		if (iosFlag.equals("1")) {
			config = weixinpayConfig;
		} else {
			config = weixinpayConfigIosQYB;

		}
	//	logger.info(".....微信环境配置参数："+config.toString());

		// UnifiedOrderRequest 赋值 TODO 共计10个参数
		uor.setSpbill_create_ip(ip);
		uor.setBody("APP叮当到微信支付");// APP叮当到微信支付
		uor.setNonce_str(nonceStr);
		uor.setAppid(config.getAppId());
		uor.setMch_id(config.getMchId());
		uor.setNotify_url(config.getNotifyUrl());
		uor.setOut_trade_no(toe.getOrderCode());
		uor.setTotal_fee(NumberUtils.y2f(toe.getPayPrice() + "") + "");
		uor.setTrade_type("APP");
		uor.setKey(config.getKey());
		String sign = WXUtil.createSign(uor);
		uor.setSign(sign);
		uor.setKey(null);
		// 将订单对象转为xml格式
		XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); // <span
																							// style="color:#ff0000;"><strong>说明3(见文末)</strong></span>
		xStream.alias("xml", UnifiedOrderRequest.class);// 根元素名需要是xml
		String orderXml = xStream.toXML(uor);
		logger.info("...........微信支付：" + orderXml);
		// 生成订单XML
		String resultMap = WXUtil.httpOrder(orderXml);
		if (resultMap != null && !("null".equals(resultMap))) {
			String paySign = null;
			UnifiedOrderRequest a = new UnifiedOrderRequest();

			a.setAppid(config.getAppId());// 微信开放平台审核通过的应用APPID
			a.setMch_id(config.getMchId());// 微信支付分配的商户号
			a.setNonce_str(nonceStr);// 随机字符串
			a.setTimestamp(seconds);
			a.setPrepay_id(resultMap);
			a.setKey(config.getKey());
			paySign = WXUtil.createSignTwo(a);
			map.put("appid", config.getAppId());
			map.put("noncestr", nonceStr);
			map.put("package", "Sign=WXPay");
			// map.put("package", "prepay_id=" + resultMap);
			map.put("partnerid", config.getMchId());
			map.put("prepayid", resultMap);
			map.put("timestamp", seconds);

			map.put("sign", paySign);
			// 入库sign
			Order orderUpParam = new Order();
			orderUpParam.setId(toe.getId());
			orderUpParam.setSigns(paySign);
			orderUpParam.setIosPayFlag(iosFlag);
			int updateOrderById = orderService.updateOrderById(orderUpParam);
			if (updateOrderById > 0) {
				return map;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	protected void initHandler() {
		register(PayMethod.WEIXIN_SDK, WxAppPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("----[微信回调]接收到的报文---" + inputString.toString());
			XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));// 说明3(见文末)
			xStream.alias("xml", UnifiedOrderRespose.class);
			UnifiedOrderRespose unifiedOrderRespose = (UnifiedOrderRespose) xStream.fromXML(inputString.toString());
			
			
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("appid", unifiedOrderRespose.getAppid()); // 微信开放平台审核通过的应用APPID
			parameters.put("attach", unifiedOrderRespose.getAttach()); // 商家数据包
			parameters.put("bank_type", unifiedOrderRespose.getBank_type()); // 微信支付分配的商户号
			parameters.put("cash_fee", unifiedOrderRespose.getCash_fee()); // 现金支付金额
			parameters.put("fee_type", unifiedOrderRespose.getFee_type()); // 货币种类
			parameters.put("is_subscribe", unifiedOrderRespose.getIs_subscribe());// 是否关注公众账号
			parameters.put("mch_id", unifiedOrderRespose.getMch_id()); // 商户号
			parameters.put("nonce_str", unifiedOrderRespose.getNonce_str());
			parameters.put("openid", unifiedOrderRespose.getOpenid());// 用户标识
			parameters.put("out_trade_no", unifiedOrderRespose.getOut_trade_no()); // 商户订单号
			parameters.put("result_code", unifiedOrderRespose.getResult_code()); // 业务结果
			// parameters.put("return_code",
			// unifiedOrderRespose.getReturn_code());
			parameters.put("time_end", unifiedOrderRespose.getTime_end()); // 支付完成时间
			parameters.put("total_fee", unifiedOrderRespose.getTotal_fee()); // 总金额
			parameters.put("trade_type", unifiedOrderRespose.getTrade_type()); // 交易类型APP
			parameters.put("transaction_id", unifiedOrderRespose.getTransaction_id()); // 微信支付订单号
			// 反校验签名
			String sign = null; 

			
			
			
			logger.info("开始进入支付成功方法里：");
			if (null != unifiedOrderRespose && "SUCCESS".equals(unifiedOrderRespose.getReturn_code())) {
				logger.info("已经进入支付成功方法里------：unifiedOrderRespose"+unifiedOrderRespose.toString());
				if (StringUtils.isBlank(unifiedOrderRespose.getOut_trade_no())) {
					return false;
				}
				return processBusiness(unifiedOrderRespose);
			} else {
				return false;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		Order orderParam = new Order();
		orderParam.setOrderCode(unifiedOrderRespose.getOut_trade_no());
		List<Order> selectOrder = orderService.selectOrder(orderParam);
		Order order = new Order();
		if (selectOrder != null && selectOrder.size() > 0) {
			order = selectOrder.get(0);
			logger.info("......回调排查信息：  订单 "+order.toString());
			if (StringUtils.isBlank(unifiedOrderRespose.getSign())) {// 签名为空
				return false;
			}
			
			String orderStatus = order.getOrderStatus();
			if (orderStatus.equals(OrderStatus.TO_PAY.getStatus())) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("......支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {
				

				} else {
					userPaymentTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyyMMddHHmmss");
				logger.info("......转换后支付时间" + string2Date);
				// 1 修改订单
				Order orderUpParam = new Order();
				orderUpParam.setId(order.getId());
				orderUpParam.setOrderStatus(OrderStatus.TO_ARRIVE.getStatus());
				orderUpParam.setPayTime(string2Date);
				orderUpParam.setPaymentNo(unifiedOrderRespose.getOpenid());
				orderUpParam.setPayTransNo(unifiedOrderRespose.getTransaction_id());
				orderUpParam.setPayType(PayMethod.WEIXIN_SDK.getCode());
				int updateOrderById = orderService.updateOrderById(orderUpParam);
				if (updateOrderById > 0) {
					////////
					// 查询优惠券
					List<Coupon> tce = null;
					logger.info("......修改订单状态成功  更改优惠券");
					if (StringUtils.isNotBlank(order.getPersonalCode())) {
						Map<String, String> map1 = new HashMap<>();
						Coupon cpParam = new Coupon();
						cpParam.setUserAccount(order.getSenderPhone());
						cpParam.setCouponCode(order.getPersonalCode());
						tce = orderService.selectCoupon(cpParam);
						if (tce != null & tce.size() > 0) {
							Coupon cpUpdateParam = new Coupon();
							cpUpdateParam.setId(tce.get(0).getId());
							cpUpdateParam.setStatus("1");
							cpUpdateParam.setUseTime(new Date());
							int updateCoupon = orderService.updateCoupon(cpUpdateParam);
							if (updateCoupon > 0) {
								logger.info("......修改订单状态成功  更改优惠券成功返回true");

								return true;
							} else {
								logger.info("......修改订单状态成功  更改优惠券失败返回false");

								return false;
							}
						} else {
							return true;
						}
					}
					// push to driver
					Driver driverSelectParam = new Driver();
					driverSelectParam.setId(order.getDriverId());
					List<Driver> driverList = orderService.selectDriver(driverSelectParam);
					if (driverList != null && driverList.size() > 0) {
						Driver driver = driverList.get(0);

						if (StringUtils.isNotBlank(driver.getDeviceToken())) {
							Push push = new Push();
							push.setPtype(1);
							push.setPushoid(order.getOrderCode());
							push.setContext("订单支付成功，已收到款项" + order.getPayPrice() + "元");// 要发送的内容
							push.setDisplayType("notification");// message:
																// 消息，通知：notification
							push.setOperationType(1);// 用户类型：1司机，2发货端
							push.setPushClient("driverPushClient");// 使用的推送Client
																		// 是往发货端：consignerPushClient
																		// 或
																		// 司机端发送：driverPushClient。
							push.setPushType("listcast");// unicast：单播
															// //
															// listcast：列表
							push.setTitle("订单支付成功"); // 发送的标题
							push.setTokenStr(new String[] { driver.getDeviceToken() }); // 要发送手机的token
							// ios & android推送公共调用方法
							pushToAppIService.pushCommon(push);
							return true;
						}
						return true;
					}

					return true;

				} else {
					return false;
				}

			} else {
				logger.info("......订单"+order.getOrderCode()+"...状态 "+orderStatus+"...不处理 返回true");
				return true;
			}

		} else {
			return false;
		}
	}

}
